package com.easy.order.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.bean.*;
import com.easy.common.service.*;
import com.easy.order.mapper.OrderMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Service
@DubboService
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderBean> implements IOrderService {
    @DubboReference
    private IUserService userService;
    @DubboReference
    private ISeatService seatService;
    @DubboReference
    private IConcertService concertService; // 新增演唱会服务引用
    @DubboReference
    private IVenueService venueService; // 新增场馆服务
    @DubboReference
    private ISeatPriceService seatPriceService;

    @Override
    public OrderBean getOrderById(Integer id) {
        return super.getById(id);
    }

    @Override
    public int addOrder(OrderBean order) {
        if (super.save(order)) {
            return 1;
        }
        return 0;
    }

    @Override
    public int uploadOrder(OrderBean order) {
        return super.updateById(order)?1:0;
    }

    @Override
    public int deleteOrder(Integer id) {
        return super.removeById(id)?1:0;
    }

    @Override
    public int reverseStatus(Integer id) {
        OrderBean order = super.getById(id);
        if(order!=null){
            order.setIsdel(order.getIsdel()==1?0:1);
        }
        if(super.updateById(order)){
            return 1;
        }
        return 0;
    }

    @Override
    public List<OrderBean> getAll(OrderBean order) {
        LambdaQueryWrapper<OrderBean> queryWrapper = new LambdaQueryWrapper<>();
        return super.list(queryWrapper);
    }



    @Override
    public IPage<OrderBean> getPage(OrderBean order, Page<OrderBean> page) {
        LambdaQueryWrapper<OrderBean> queryWrapper = new LambdaQueryWrapper<>();
        if(order!=null&& order.getOrderno()!=null&& !order.getOrderno().isEmpty()) {
            queryWrapper.like(OrderBean::getOrderno, order.getOrderno());
        }
        if(order!=null&& order.getUserid()!=null) {
            queryWrapper.like(OrderBean::getUserid, order.getUserid());
        }
        return super.page(page,queryWrapper);
    }

//    @Override
//    public IPage<OrderBean> getOrderWithUserNickname(Page<OrderBean> page) {
//        IPage<OrderBean> ipage = super.page(page,new QueryWrapper<OrderBean>());
//        ipage.getRecords().forEach(order -> {
//            UserBean user = userService.getUserById(order.getUserid());
////            System.out.println("order.getUserid()"+order.getUserid());
////            System.out.println( user);
//            order.setUserNickname(user.getNickname());
////            SeatBean seat = seatService.getSeatById(order.getSeatid());
////            order.setSeatArea(seat.getArea());
//        });
//        return ipage;
//    }
    @Override
    public IPage<OrderBean> getOrderWithUserNickname(Page<OrderBean> page) {
        IPage<OrderBean> ipage = super.page(page, new QueryWrapper<OrderBean>());
        ipage.getRecords().forEach(order -> {
            // 设置用户昵称
            UserBean user = userService.getUserById(order.getUserid());
            if (user != null) {
                order.setUserNickname(user.getNickname());
            }

            // 新增：设置演唱会信息
            ConcertBean concert = concertService.getConcertById(order.getConcertid());
            if (concert != null) {
                order.setConcertTitle(concert.getTitle());
                order.setArtist(concert.getArtist());
                order.setStartdate(concert.getStartdate());
                order.setVenueid(concert.getVenueid());

                // 如果需要场馆名称，可以通过venueService获取
                // VenueBean venue = venueService.getVenueById(concert.getVenueid());
                // if (venue != null) {
                //     order.setVenueName(venue.getName());
                //     order.setVenueAddress(venue.getAddress());
                // }
            }

            // 设置座位信息
            SeatBean seat = seatService.getSeatById(order.getSeatid());
            if (seat != null) {
                order.setSeatArea(seat.getArea());
            }
            // 获取座位价格信息
            SeatPriceBean seatPrice = seatPriceService.getSeatPriceById(order.getSeatpriceid());
            if (seatPrice != null) {
                order.setSeatprice(seatPrice.getPrice());
            }
        });
        return ipage;
    }

//    // 新增方法：根据用户ID查询订单（带演唱会信息）
//    @Override
//    public IPage<OrderBean> getOrdersByUserIdWithConcertInfo(Integer userId, Page<OrderBean> page) {
//        QueryWrapper<OrderBean> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("userid", userId);
//        queryWrapper.orderByDesc("createtime"); // 按创建时间倒序
//
//        IPage<OrderBean> ipage = super.page(page, queryWrapper);
//        ipage.getRecords().forEach(order -> {
//            // 设置用户昵称
//            UserBean user = userService.getUserById(order.getUserid());
//            if (user != null) {
//                order.setUserNickname(user.getNickname());
//            }
//
//            // 设置演唱会信息
//            ConcertBean concert = concertService.getConcertById(order.getConcertid());
//            if (concert != null) {
//                order.setConcertTitle(concert.getTitle());
//                order.setArtist(concert.getArtist());
//                order.setStartdate(concert.getStartdate());
//                // 可以设置更多演唱会字段...
//            }
//
//            // 设置座位信息
//            SeatBean seat = seatService.getSeatById(order.getSeatid());
//            if (seat != null) {
//                order.setSeatArea(seat.getArea());
//            }
//        });
//        return ipage;
//    }
//
//    // 新增方法：多条件查询订单（带演唱会信息）
//    @Override
//    public IPage<OrderBean> getOrdersByMultiCondition(Integer userId, String status, Date startDate, Date endDate, Page<OrderBean> page) {
//        QueryWrapper<OrderBean> queryWrapper = new QueryWrapper<>();
//
//        // 用户ID条件
//        if (userId != null) {
//            queryWrapper.eq("userid", userId);
//        }
//
//        // 状态条件
//        if (status != null && !status.isEmpty()) {
//            queryWrapper.eq("status", status);
//        }
//
//        // 时间范围条件
//        if (startDate != null && endDate != null) {
//            queryWrapper.between("createtime", startDate, endDate);
//        }
//
//        queryWrapper.orderByDesc("createtime");
//
//        IPage<OrderBean> ipage = super.page(page, queryWrapper);
//        ipage.getRecords().forEach(order -> {
//            // 设置用户昵称
//            UserBean user = userService.getUserById(order.getUserid());
//            if (user != null) {
//                order.setUserNickname(user.getNickname());
//            }
//
//            // 设置演唱会信息
//            ConcertBean concert = concertService.getConcertById(order.getConcertid());
//            if (concert != null) {
//                order.setConcertTitle(concert.getTitle());
//                order.setArtist(concert.getArtist());
//                order.setStartdate(concert.getStartdate());
//                // 可以设置更多演唱会字段...
//            }
//
//            // 设置座位信息
//            SeatBean seat = seatService.getSeatById(order.getSeatid());
//            if (seat != null) {
//                order.setSeatArea(seat.getArea());
//            }
//        });
//        return ipage;
//    }


    @Override
    public IPage<OrderBean> getOrdersByUserIdWithConcertInfo(Integer userId, Page<OrderBean> page) {
        // 明确指定查询的字段，避免查询不存在的字段
        QueryWrapper<OrderBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "userid", "seatid", "orderno", "status", "createtime",
                "paytime", "expiretime", "isdel", "concertid", "seatpriceid");
        queryWrapper.eq("userid", userId);
        queryWrapper.eq("isdel", 0); // 只查询未删除的订单
        queryWrapper.orderByDesc("createtime");

        IPage<OrderBean> ipage = super.page(page, queryWrapper);
        enrichOrderWithAdditionalInfo(ipage.getRecords());
        return ipage;
    }

    @Override
    public IPage<OrderBean> getOrdersByMultiCondition(Integer userId, String status, Date startDate, Date endDate, Page<OrderBean> page) {
        // 明确指定查询的字段
        QueryWrapper<OrderBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "userid", "seatid", "orderno", "status", "createtime",
                "paytime", "expiretime", "isdel", "concertid", "seatpriceid");

        // 用户ID条件
        if (userId != null) {
            queryWrapper.eq("userid", userId);
        }

        // 状态条件
        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status", status);
        }

        // 时间范围条件
        if (startDate != null && endDate != null) {
            queryWrapper.between("createtime", startDate, endDate);
        }

        queryWrapper.eq("isdel", 0); // 只查询未删除的订单
        queryWrapper.orderByDesc("createtime");

        IPage<OrderBean> ipage = super.page(page, queryWrapper);
        enrichOrderWithAdditionalInfo(ipage.getRecords());
        return ipage;
    }

    /**
     * 为订单列表填充额外的信息（用户昵称、演唱会信息、座位信息）
     */
    private void enrichOrderWithAdditionalInfo(List<OrderBean> orders) {
        for (OrderBean order : orders) {
            try {
                // 设置用户昵称
                UserBean user = userService.getUserById(order.getUserid());
                if (user != null) {
                    order.setUserNickname(user.getNickname());
                }
            } catch (Exception e) {
                log.warn("获取用户信息失败: {}");
                order.setUserNickname("未知用户");
            }

            try {
                // 设置演唱会信息
                ConcertBean concert = concertService.getConcertById(order.getConcertid());
                if (concert != null) {
                    order.setConcertTitle(concert.getTitle());
                    order.setArtist(concert.getArtist());
                    order.setStartdate(concert.getStartdate());
                    order.setPhoto(concert.getPhoto()); // 设置演唱会图片

                    // 设置场馆信息
                    if (concert.getVenueid() != null) {
                        VenueBean venue = venueService.getVenueById(concert.getVenueid());
                        if (venue != null) {
                            order.setVenueName(venue.getName());
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("获取演唱会信息失败: {}");
                order.setConcertTitle("未知演唱会");
                order.setArtist("未知艺人");
            }

            try {
                // 设置座位信息
                SeatBean seat = seatService.getSeatById(order.getSeatid());
                if (seat != null) {
                    order.setSeatArea(seat.getArea());
                }
            } catch (Exception e) {
                log.warn("获取座位信息失败: {}");
                order.setSeatArea("未知区域");
            }
            try {
                // 获取座位价格信息
                SeatPriceBean seatPrice = seatPriceService.getSeatPriceById(order.getSeatpriceid());
                if (seatPrice != null) {
                    order.setSeatprice(seatPrice.getPrice());
                }
            } catch (Exception e) {
                log.warn("获取座位价格信息失败: {}");
                order.setSeatprice(BigDecimal.ZERO);
            }
        }
    }



}
